#include "stm32f1xx_hal.h"
#include "cmsis_os.h"
#include <stdio.h>
#include "systemconf.h"
#include  <string.h>
#include <stdarg.h>
#include "stdport.h"
#include "sim800c_fs.h"


extern unsigned short milliscond ;
extern unsigned char Time[6] ;

#define ELOG_LINE_BUF_SIZE                       512

static char log_buf[ELOG_LINE_BUF_SIZE] = { 0 };


static void elog_port_output(const char *log, size_t size) {
    /* output to terminal */
    printf("%.*s", size, log);
}

static char c_timestamp[16] ;

void debug_print(unsigned char level, const char *format , ...)
{
    va_list args;
    int fmt_result;
    size_t log_len = 0;
            
    sprintf(c_timestamp , "[%02d:%02d:%02d:%03d] " , Time[3] , Time[4] , Time[5] , milliscond) ;
    
    if(level < DEBUG_LVL)                                   return ;
    if(0 == (device.status & EXTSTAT ))                     return ;
    if(0 == (device.status & DEBUGMESSAGE))                 return ;
    if(1 == msgfilter(format))                              return ;

    va_start(args, format);
    
    /* package log data to buffer */
    fmt_result = vsnprintf(log_buf, ELOG_LINE_BUF_SIZE, format, args);
    
    /* output converted log */
    if ((fmt_result > -1) && (fmt_result <= ELOG_LINE_BUF_SIZE)) {
        log_len = fmt_result;
    } else {
        log_len = ELOG_LINE_BUF_SIZE;
    }
    
    if(device.status & DEBUGMESSAGETIME)    
    {
        printf(c_timestamp) ;  
    }
    elog_port_output(log_buf, log_len);
    
    if((level >= DEBUG_NORMAL) && (device.status & SIM800C_FS_LOG))
    {
        short i ;
        
        if(log_len > 1024 - 15)     log_len = 1024 - 15 ;
        
        for(i = log_len ; i >= 0 ; i --)
        {
            log_buf[15 + i] = log_buf[i] ;
        }
        
        memcpy(log_buf , c_timestamp , 15) ;
        sim800c_fs_write(log_buf , log_len + 15) ;
    }
        
    va_end(args);
    
}

